<template>
  <el-upload
    v-loading="loading"
    class="uploader"
    :class="{ 'hover-mask': value }"
    action="https://up-z2.qiniup.com"
    :show-file-list="false"
    :data="param"
    accept="image/*"
    :on-success="handleSuccess"
    :before-upload="handlebeforeUpload"
  >
    <img v-if="value" :src="value" class="avatar" />
    <i class="el-icon-plus uploader-icon"></i>
  </el-upload>
</template>

<script>
// import axios from "axios";
export default {
  props: {
    value: String,
    // eslint-disable-next-line vue/require-prop-type-constructor
    required: true
  },
  data() {
    return {
      loading: "",
      param: {
        token: ""
      }
    };
  },
  methods: {
    handleSuccess(res, file) {
      this.loading = false;
      console.log(file);
      // 如果不传 key 参数，就使用七牛自动生成的 hash 值，如果传递了 key 参数，那么就用返回的 key 值
      const { hash } = res;
      // 拼接得到图片 url
      const imageUrl = "your domain prefix" + hash;
      // 触发事件 input，父组件会修改绑定的 value 值
      this.$emit("input", imageUrl);
    },
    handlebeforeUpload(file) {
      // 这里做可以做文件校验操作
      const isImg = /^image\/\w+$/i.test(file.type);
      if (!isImg) {
        this.$message.error("只能上传 JPG、PNG、GIF 格式!");
        return false;
      }
      // return new Promise((resolve, reject) => {
      //   this.loading = true;
      //   获取token
      //   const tokenUrl = "http://xxx/upload";
      //   axios
      //     .get(tokenUrl)
      //     .then(res => {
      //       const { token } = res.data.data;
      //       this.param.token = token;
      //       resolve(true);
      //     })
      //     .catch(err => {
      //       this.loading = false;
      //       reject(err);
      //     });
      // });
    }
  }
};
</script>

<style scoped lang="scss">
.uploader {
  position: absolute;
  left: 100px;
  width: 130px;
  height: 130px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  &:hover {
    border-color: #409eff;
  }
  // .el-upload {
  //   position: relative;
  //   width: 100%;
  //   height: 100%;
  //   overflow: hidden;
  // }
}
.uploader-icon {
  // position: absolute;
  // top: 0;
  // left: 0;
  // width: 100%;
  // height: 100%;
  line-height: 128px;
  // text-align: center;
  font-size: 28px;
  color: #8c939d;
}
.avatar + .uploader-icon {
  opacity: 0;
}
.avatar {
  width: 128px;
  height: 128px;
  display: block;
  border-radius: 6px;
}
.hover-mask:hover .uploader-icon {
  opacity: 1;
  background-color: rgba(0, 0, 0, 0.2);
  color: #fff;
}
</style>
